import Vue from 'vue'

import fixBottom from '@/components/fixBottom'
// import XButton from 'vux/src/components/x-button/index.vue'
import { Button, ButtonGroup } from 'vue-ydui/dist/lib.px/button'
import { Toast } from 'vue-ydui/dist/lib.px/dialog'


// Vue.component(Loadmore.name, Loadmore);
Vue.component(Button.name, Button)
Vue.component(ButtonGroup.name, ButtonGroup)

export default {
  name: 'home',
  data() {
    return {
      goods_name:true,
      goodNumber: 0,
      containerHeight: "",
      twoClass: [], // 二级分类列表
      goods: [], // 商品街列表
      activeFlag: 0, // 选中的列表
      quentity: 1,
      containerId: '', // 货架Id
      companyId: '', //公司id
      oneClass: [], // 左侧货柜列表
      number: '',
      Imgs:'',
      companys:[]
      // openid:'',
    }
  },
  components: {
    fixBottom,
    // XButton,
  },

  methods: {
    changeTab: function (value, index) { // 获取指定标签下的商品
      console.log(value)
      this.activeFlag = index;
      this.containerId = value.id
      this.getGoods()
    },

    getGoods() { // 获取商品列表
      this.goods = []
      this.axios.get('/layered/list', {
        params: {
          sid: this.containerId
        }
      }).then(res => {
        console.log(res)
        this.twoClass = res.data.datas
        // console.log(this.twoClass) 
        this.twoClass.forEach(value => {
          // console.log(value)
          value.layered_goods.forEach(val => {
            this.goods.push(val)
          })
        })
        // console.log('getGoods', this.goods)
      })
    },

    getImg(){//获取背景图
      this.axios.get('/image/info',{
        params:{
          openid:sessionStorage.getItem('openid')
        }
      }).then(res => {
        console.log(res)
        this.Imgs = res.data.datas
        console.log('this.Imgs')
      })
    },

    getCompany(){//获取公司
      this.axios.get('/company/info',{
        params:{
          openid:sessionStorage.getItem('openid'),
          cid:1
        }
      }).then(res => {
        console.log(this.companys)
        this.companys = res.data.datas
        console.log(this.companys)
      })
    },

    changeQuentity(item, num) { // 加减购物车数量,0表示数量增加，1表示数量减少
      if (num > 0) {
        if (typeof item.quentity == 'undefined') {
          this.$set(item, 'quentity', 1)
        }
        else if (item.quentity >= 1 && item.quentity <= item.number) {
          item.quentity++;
        }
        else if (item.quentity >= item.number) {
          item.quentity = item.number
          Toast({
            mes: '库存不足',
            timeout: 400
          });
        }
        else {
          item.quentity = 1;
        }
        this.goodNumber++ // 底部数量加
      } else {
        if (item.quentity < 1) {
          // item.quentity = 0
          // console.log('if item.quentity', item.quentity)
          // localStorage.removeItem('item' + item.id);
        }
        else if (item.quentity >= 1 && item.number >= item.quentity) {
          item.quentity--
          // console.log('else item.quentity', item.quentity)
          // if (item.quentity == 0) {
          //   localStorage.getItem('item' + i).split(',')[0]
          //   console.log('item 0',item)
          // }
          this.goodNumber-- // 底部数量减
        }
        // else{
        //   Toast({
        //     mes: '已经为零了！',
        //     timeout: 400
        //   });
        // }
      }
      this.addShop(item, num)
    },
    addShop: function (good, num) { // 加入购物车
      let i = 1;
      let quent = good.quentity;
      while (localStorage.getItem('item' + good.id) != null) {
        if ((localStorage.getItem('item' + good.id).split(',')[0]) == (good.id + '')) { //判断该商品是已经存在
          if (num > 0) { // 数量增加
            console.log(quent)
            if (quent < good.number) {
              quent = parseInt(localStorage.getItem('item' + good.id).split(',')[1]) + 1;
              Toast({
                mes: '添加成功',
                timeout: 400
              });
            } else if (quent >= good.number) {
              quent = good.number
              Toast({
                mes: '库存不足',
                timeout: 400
              });
            }

          } else { // 数量减少
            if (good.quentity < 1) {
              good.quentity = 0
              console.log('addshop', good.quentity)
              localStorage.removeItem('item' + good.id);
              return
            }
            quent = parseInt(localStorage.getItem('item' + good.id).split(',')[1]) - 1;
            Toast({
              mes: '减少数量',
              timeout: 400
            });
          }
          good.quentity = quent
          break;
        }
        i++
      }
      console.log('containerId', this.containerId)
      localStorage.setItem('item' + good.id, good.id + ',' + quent + ',' + this.containerId + ',' + this.companyId);
    },
  },
  mounted() {
    this.getImg()
    this.getCompany()
    this.$nextTick(function () {
      // console.log('mounted this.goods', this.goods)

    })
  },
  created() { 
    // console.log(sessionStorage.getItem('openid'))
    var taskQuery = new window.TaskQuery().create()

    var task1 = new Task().create(handel => { // 获取公司的货架
      this.axios.get('/company/shelves/list', {
        params: {
          openid:sessionStorage.getItem('openid'),
          cid: 1, 
        }
      }).then(res => {
        // console.log(res)
        this.oneClass = res.data.datas
        // console.log(this.oneClass)
        this.containerId = res.data.datas[0].id
        // console.log('this.containerId',this.containerId)
        handel.ready()
      })
    })

    var task2 = new Task().create(handel => { // 获取对应货架下的商品列表
      this.axios.get('/layered/list', {
        params: {
          openid:sessionStorage.getItem('openid'),
          sid: this.containerId
        }
      }).then(res => {
        // console.log(res)
        this.twoClass = res.data.datas
        this.twoClass.forEach(value => {
          // console.log(value)
          let lid = value.id
          // console.log(lid)
          localStorage.setItem('lid',lid)
          // console.log(localStorage.getItem('lid'))
          value.layered_goods.forEach(val => {
            // console.log(val)
            localStorage.setItem('price',val.sell_price)
            // console.log(localStorage.getItem('price'))
            this.goods.push(val)
          })
        })
        
        for (var i = 0; i < localStorage.length; i++) { // 循环本地存储的商品数量,显示在商品列表商
          let key = localStorage.key(i);
          if (key.match(/^item[0-9]+$/)) {
            this.goodNumber += parseInt(localStorage.getItem(key).split(',')[1])
            let valueId = localStorage.getItem(key).split(',')[0]; //获取商品id
            for (let j = 0; j < this.goods.length; j++) { // 循环已经展示的商品数组
              if (valueId == (this.goods[j].id + '')) {
                if (typeof this.goods[j].quentity == 'undefined') {
                  this.$set(this.goods[j], 'quentity', 1)
                  this.goods[j].quentity = localStorage.getItem(key).split(',')[1];
                  // console.log(this.goods[j].quentity)
                }
              }
            }
          }
        }
      })
      console.log('this.goodNumbe', this.goodNumber)
    })

    var task3 = new Task().create(handel =>{//获取首页背景图
      this.axios.get('/image/info',{
        params:{
          openid:sessionStorage.getItem('openid')
        }
      }).then(res => {
        console.log(res)
        this.Imgs = res.data.datas
      })
    })

    var task4 = new Task().create(handel =>{//获取公司
      this.axios.get('/company/info',{
        params:{
          openid:sessionStorage.getItem('openid'),
          cid:1
        }
      }).then(res => {
        console.log(res)
        this.Imgs = res.data.datas
      })
    })

    //把任务丢入任务队列中
    taskQuery.push(task1)
    taskQuery.push(task2)
    taskQuery.push(task3)
    // taskQuery.push(task4)

    //开始执行任务
    taskQuery.run()
    this.getGoods()
    // this.getImgs()
  },
}
